<template>
  <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="elpane">
    <el-form-item label="" prop="username" style="font-size: 30px">
      <el-input class="logins" size="default" type="text" v-model="ruleForm.username" autocomplete="off"
                placeholder="请输入用户名"></el-input>
    </el-form-item>
    <el-form-item label="" prop="email">
      <el-input class="logins" type="email" v-model="ruleForm.email" placeholder="请输入邮箱"></el-input>
    </el-form-item>
    <el-form-item label="" prop="pass">
      <el-tooltip placement="right">
        <template style="width: 140px" v-if="ruleForm.pass.length === 0" #content>
          <span>密码长度至少为8位；</span><br>
          <span>密码不能是键盘上的连续字符序列、相同字符；</span><br>
          <span>密码必须包含数字、小写字母、大写字母、<br>特殊符号中的至少三类；</span>
        </template>
        <template v-else #content>
          <span :style="{ color: isLenth ? '#0256ff' : '#67c23a' }">
            <el-icon v-if="isLenth"><Select/></el-icon>
            <el-icon v-else><CloseBold/></el-icon>密码长度至少为8位</span><br>
          <span :style="{ color: isCoiled ? '#0256ff' : '#67c23a' }">
            <el-icon v-if="isCoiled"><Select/></el-icon>
            <el-icon v-else><CloseBold/></el-icon>密码不能是键盘上的连续字符序列、相同字符</span><br>
          <span :style="{ color: isContain? '#0256ff' : '#67c23a' }">
            <el-icon v-if="isContain"><Select/></el-icon>
            <el-icon v-else><CloseBold/></el-icon>密码必须包含数字、小写字母、大写字母、<br>特殊符号中的至少三类</span>
        </template>
        <el-input class="logins" @input="passwordVerification" type="password" v-model="ruleForm.pass" autocomplete="on"
                  show-password
                  placeholder="请输入密码"/>
      </el-tooltip>
    </el-form-item>
    <el-form-item label="" prop="checkPass">
      <el-input class="logins" type="password" v-model="ruleForm.checkPass" autocomplete="on" show-password
                placeholder="请确认密码"></el-input>
    </el-form-item>
    <el-form-item label="" prop="code">
      <div class="verify-wrapper">
        <el-input style="width: 190px" type="text" maxlength="6" suffix-icon="el-icon-lock"
                  placeholder="请输入验证码" v-model="ruleForm.code"/>
        <el-button class="btn-orange" style="margin-left: 10px" :plain="true" :disabled="disabled"
                   @click="tackBtn">{{ valiBtn }}
        </el-button>
      </div>
    </el-form-item>
  </el-form>
  <el-button style="width: 150px;margin-top: -10px" type="success" @click="enroll">注册</el-button>
</template>
<script>
import {router} from "@/router";
import {getLoginCodeApi, registerApi} from "@/pages/userLogin/index.js";

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      }else if (!this.isCoiled || !this.isLenth || !this.isContain){
        callback(new Error('请输入正确格式的密码'));
      }
      else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      disabled: false,
      isLenth: false,
      isCoiled: false,
      isContain: false,
      valiBtn: '获取验证码',
      ruleForm: {
        pass: '',
        checkPass: '',
        email: '',
        username: '',
        code: '',
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
        ],
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {validator: validatePass2, trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']},
          {
            validator: (rule, value, callback) => {
              const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
              if (!emailRegex.test(value)) {
                callback(new Error('请输入正确的邮箱地址'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    enroll() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.isLenth && this.isCoiled && this.isContain) {
            registerApi(this.ruleForm).then(res => {
              if (res.code === 0) {
                this.$message.success('注册成功');
                router.push("/userLogin")
              } else {
                this.$message(res.data.message)
              }
            })
          } else {
            this.$message.error('密码不符合要求，请重新输入')
          }
        } else {
          ElMessage.error('请检查表单信息');
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    tackBtn() {
      //验证码倒数60秒
      // 验证电子邮件地址的正则表达式函数
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

      if (this.ruleForm.email === "" || emailRegex.test(this.ruleForm.email) === false) {
        this.$message('请输入正确的邮箱');
      } else {
        let time = 60;
        getLoginCodeApi(this.ruleForm.email).then(res => {
          if (res.code === 0) {
            console.log("发送成功" + res.data)
          } else {
            console.log("发送失败" + res.data)
          }
        }).catch(error => {

        })
        let timer = setInterval(() => {
          if (time == 0) {
            clearInterval(timer);
            this.valiBtn = '获取验证码';
            this.disabled = false;
          } else {
            this.disabled = true;
            this.valiBtn = time + '秒后重试';
            time--;
          }
        }, 1000);
      }

    },
    passwordVerification() {
      console.log(this.ruleForm.pass, "data")
      // 密码长度至少为8位
      if (this.ruleForm.pass.length >= 8){
        this.isLenth = true;
      }else if (this.ruleForm.pass.length < 8){
        this.isLenth = false;
      }
      // 2. 检查是否是键盘上的连续字符序列
        const isContinuous =this.isContinuousChar(this.ruleForm.pass);
        if (!isContinuous) {
          this.isCoiled = true;
        } else {
          this.isCoiled = false;
        }
      // 3. 检查是否包含数字、小写字母、大写字母、特殊符号中的至少三类
      const hasDigit = /\d/.test(this.ruleForm.pass);
      const hasLower = /[a-z]/.test(this.ruleForm.pass);
      const hasUpper = /[A-Z]/.test(this.ruleForm.pass);
      const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(this.ruleForm.pass);
      const categories = [hasDigit, hasLower, hasUpper, hasSpecial].filter(Boolean);
      if (categories.length >= 3) {
        this.isContain=true
      } else {
        this.isContain=false
      }
    },

    /**
     * 是否包含3个及以上字典连续字符
     */
    isContinuousChar(password) {
      // 将密码转换为小写，忽略大小写
      password = password.toLowerCase();
      // 获取密码的字符数组
      const chars = password.split('');
      // 判断是否存在3个及以上的连续字符
      // 示例： 'abc'，'def'
      if (this.hasSequentialCharacters(chars, 3)) {
        console.log(`Password contains 3 or more sequential characters: ${chars}`);
        return true;
      }
      // 判断是否存在3个及以上的重复字符
      // 示例： 'aaa'，'bbb'，'ddd'
      if (this.hasRepeatedCharacters(chars, 3)) {
        console.log(`Password contains 3 or more repeated characters: ${chars}`);
        return true;
      }
      return false;
    },
    // 判断是否存在N个及以上的连续字符
    hasSequentialCharacters(chars, n) {
      const charCode = chars.map(char => char.charCodeAt(0));
      let count = 1;
      for (let i = 1; i < charCode.length; i++) {
        if (Math.abs(charCode[i] - charCode[i - 1]) === 1) {
          count++;
          if (count >= n) {
            return true;
          }
        } else {
          count = 1; // 重置计数
        }
      }
      return false;
    },
    // 判断是否存在N个及以上的重复字符
    hasRepeatedCharacters(chars, n) {
      let count = 1;
      for (let i = 1; i < chars.length; i++) {
        if (chars[i] === chars[i - 1]) {
          count++;
          if (count >= n) {
            return true;
          }
        } else {
          count = 1; // 重置计数
        }
      }
      return false;
    }
  }
}
</script>

<style scoped>

.el-input {
  font-size: 15px;
}

.elpane {
  display: flex;
  justify-content: center; /* 横向居中 */
  align-items: center; /* 子内容纵向居中 */
  flex-direction: column; /* 子元素内部堆叠方式 */
}

.el-form-item__error {
  font-size: 16px;
}

.logins {
  width: 300px;
  justify-content: center;
}

.zhuce {
  margin-top: 20px;
}

</style>
